package org.jeecg.modules.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccqtgb.sxp.partner.security.bo.RequestData;
import com.ccqtgb.sxp.partner.security.bo.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.api.utils.ApiDataUtils;
import org.jeecg.modules.api.utils.ValidatorUtils;
import org.jeecg.modules.api.vo.param.CustomersCheckVo;
import org.jeecg.modules.api.vo.param.FindCustomersParamVo;
import org.jeecg.modules.api.vo.rest.CustomersCompanyBalanceVo;
import org.jeecg.modules.api.vo.rest.CustomersRestVo;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.zcgl.entity.*;
import org.jeecg.modules.zcgl.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Api(tags = "三峡银行接口-客户信息")
@RestController
@RequestMapping("/api/bank/customers")
@Slf4j
public class CustomersApiController {

    @Autowired
    private ICustomerInfoService customerInfoService;
    @Autowired
    private ICustomerBalanceService customerBalanceService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ILeaseContractInfoService contractInfoService;
    @Autowired
    private IAssetInfoService assetInfoService;
    @Autowired
    private IReceivablesInfoService receivablesInfoService;

    @ApiOperation(value = "获取客户信息", notes = "获取客户信息")
    @PostMapping("/findCustomers")
    public ResponseData<String> findCustomers(@RequestBody String message) {

        RequestData<CustomersCheckVo> dataReslt = ApiDataUtils.getRequestData(message, CustomersCheckVo.class);
        try {
            CustomersCheckVo vo = dataReslt.getBody();
            String validateResult = ValidatorUtils.validateFastStr(vo);
            if (validateResult != null) {
                return ApiDataUtils.getResponseData(Result.errorValidation(validateResult), dataReslt.getHead());
            }

            //查询客户信息
            LambdaQueryWrapper<CustomerInfo> queryWrapper = new LambdaQueryWrapper<>();
            CustomerInfo customerInfo = new CustomerInfo();
            BeanUtils.copyProperties(vo, customerInfo);
            if (StringUtils.isNotBlank(customerInfo.getCode())){
                customerInfo.setCode(customerInfo.getCode().toUpperCase());
            }
            queryWrapper.setEntity(customerInfo);
            CustomerInfo info = customerInfoService.getOne(queryWrapper, false);
            if (info == null) {
                return ApiDataUtils.getResponseData(Result.error("用户不存在!"), dataReslt.getHead());
            }

            return ApiDataUtils.getResponseData(Result.ok(getCustomersRestVo(info)), dataReslt.getHead());
        } catch (Exception e) {
            e.printStackTrace();
            return ApiDataUtils.getResponseData(Result.error(e.getMessage()), dataReslt.getHead());
        }
    }

    @ApiOperation(value = "根据ID获取客户信息", notes = "根据ID获取客户信息")
    @PostMapping("/getCustomersById")
    public ResponseData<String> getCustomersById(@RequestBody String message) {
        RequestData<FindCustomersParamVo> dataReslt = ApiDataUtils.getRequestData(message, FindCustomersParamVo.class);
        try {
            FindCustomersParamVo vo = dataReslt.getBody();
            String validateResult = ValidatorUtils.validateFastStr(vo);
            if (validateResult != null) {
                return ApiDataUtils.getResponseData(Result.errorValidation(validateResult), dataReslt.getHead());
            }
            CustomerInfo info = customerInfoService.getById(vo.getId());
            if (info == null) {
                return ApiDataUtils.getResponseData(Result.error("用户不存在!"), dataReslt.getHead());
            }
            return ApiDataUtils.getResponseData(Result.ok(getCustomersRestVo(info)), dataReslt.getHead());
        } catch (Exception e) {
            e.printStackTrace();
            return ApiDataUtils.getResponseData(Result.error(e.getMessage()), dataReslt.getHead());
        }
    }

    private CustomersRestVo getCustomersRestVo(CustomerInfo info) {
        CustomersRestVo restVo = new CustomersRestVo();
        BeanUtils.copyProperties(info, restVo);
        List<CustomerBalance> balances = customerBalanceService.list(new LambdaQueryWrapper<CustomerBalance>().eq(CustomerBalance::getCustomerId,info.getId()));
        List<CustomersCompanyBalanceVo> customersCompanyBalanceVoList = balances.stream().map(p->{
            CustomersCompanyBalanceVo customersCompanyBalanceVo = new CustomersCompanyBalanceVo();
            customersCompanyBalanceVo.setBalance(p.getBalance());
            customersCompanyBalanceVo.setCompanyName(sysDepartService.getNameById(p.getCompanyId()));
            BigDecimal oweBalance = BigDecimal.ZERO;
            customersCompanyBalanceVo.setContractNum("");
            customersCompanyBalanceVo.setSite("");
            if(oConvertUtils.isNotEmpty(p.getLeaseContractId())){
                LeaseContractInfo contractInfo = contractInfoService.getById(p.getLeaseContractId());
                if(contractInfo !=null){
                    customersCompanyBalanceVo.setContractNum(contractInfo.getContractNum());
                    AssetInfo assetInfo = assetInfoService.getById(contractInfo.getAssetId());
                    if(assetInfo !=null){
                        customersCompanyBalanceVo.setSite(assetInfo.getSite());
                    }
                }
            }
            List<ReceivablesInfo> receivablesInfoList = receivablesInfoService.list(new LambdaQueryWrapper<ReceivablesInfo>()
                    .eq(ReceivablesInfo::getCustomerId,p.getCustomerId())
                    .eq(ReceivablesInfo::getAmountConfirmation,"1").eq(ReceivablesInfo::getCompanyId,p.getCompanyId()));
            if(receivablesInfoList !=null && receivablesInfoList.size()>0){
                oweBalance = receivablesInfoList.stream().map(ReceivablesInfo::getUnAmountMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
            customersCompanyBalanceVo.setOweBalance(oweBalance);
            return customersCompanyBalanceVo;
        }).collect(Collectors.toList());
        restVo.setCustomersCompanyBalances(customersCompanyBalanceVoList);
        return restVo;
    }
}
